//
//  OutPutEngineViewController.m
//  AudioKitOC
//
//  Created by Hwang on 2018/5/4.
//  Copyright © 2018年 AudioKit. All rights reserved.
//

#import "OutPutEngineController.h"
#import <AVFoundation/AVFoundation.h>

@interface OutPutEngineController ()

@property (nonatomic, strong) AVAudioPlayerNode *player;
@property (nonatomic, strong) AVAudioEngine *engine;
@property (nonatomic, strong) AVAudioUnitReverb *reverb;
@property (nonatomic, strong) NSURL *outputURL;
@property (nonatomic, strong) AVAudioPCMBuffer *buffer;
@property (nonatomic, strong) AVAudioFile *audioFile;

@end

@implementation OutPutEngineController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //播放节点
    _player = [[AVAudioPlayerNode alloc] init];
    //混音节点
    _reverb = [[AVAudioUnitReverb alloc] init];
    //中厅混音效果
    [_reverb loadFactoryPreset:AVAudioUnitReverbPresetMediumHall];
    //混音干湿比：0-100
    _reverb.wetDryMix = 20;
    //读取音频文件
    NSString *file = [[NSBundle mainBundle] pathForResource:@"起风了" ofType:@"mp3"];
    _audioFile = [[AVAudioFile alloc] initForReading:[NSURL fileURLWithPath:file] error:nil];
    _buffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:_audioFile.processingFormat frameCapacity:(AVAudioFrameCount)[_audioFile length]];
    BOOL success = [_audioFile readIntoBuffer:_buffer error:nil];
    if (success) {
        
    }
    //音频引擎
    _engine = [[AVAudioEngine alloc] init];
    //加入节点
    [_engine attachNode:_player];
    [_engine attachNode:_reverb];
    //链接节点
    [_engine connect:_player to:_reverb format:_buffer.format];
    [_engine connect:_reverb to:_engine.mainMixerNode format:_buffer.format];
    
    //启动引擎
    if (!self.engine.running) {
        [self.engine startAndReturnError:nil];
    }
    //播放
    [self.player scheduleBuffer:self.buffer atTime:nil options:0 completionHandler:^{
        
    }];
    [self.player play];
    
    //监听混合节点，并且导出混合音频
    NSError *error;
    if (!self.outputURL) self.outputURL = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"mixerOutput.caf"]];
    
    AVAudioMixerNode *mainMixer = [self.engine mainMixerNode];
    AVAudioFile *mixerOutputFile = [[AVAudioFile alloc] initForWriting:self.outputURL settings:[[mainMixer outputFormatForBus:0] settings] error:&error];
    NSLog(@"%@", self.outputURL);
    NSAssert(mixerOutputFile != nil, @"mixerOutputFile is nil, %@", [error localizedDescription]);
    [self.engine.mainMixerNode installTapOnBus:0 bufferSize:4096 format:[mainMixer outputFormatForBus:0] block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
        NSError *error;
        BOOL success = NO;
        success = [mixerOutputFile writeFromBuffer:buffer error:&error];
        NSAssert(success, @"error writing buffer data to file, %@", [error localizedDescription]);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
